import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Tag,
  Space,
  Modal,
  message,
  Typography,
  Popconfirm,
  Input,
  Form,
} from 'antd';
import {
  CheckOutlined,
  CloseOutlined,
  EyeOutlined,
  CloudDownloadOutlined,
} from '@ant-design/icons';
import { 
  getPendingTorrents, 
  approveTorrent, 
  rejectTorrent 
} from '../../api/admin';
import { Torrent, TORRENT_STATUS_MAP, PROMOTION_STATUS_MAP } from '../../types';
import { formatBytes, formatDateTime } from '../../utils/format';

const { Title, Text } = Typography;
const { TextArea } = Input;

const TorrentManagement: React.FC = () => {
  const [torrents, setTorrents] = useState<Torrent[]>([]);
  const [loading, setLoading] = useState(false);
  const [rejectModalVisible, setRejectModalVisible] = useState(false);
  const [currentTorrent, setCurrentTorrent] = useState<Torrent | null>(null);
  const [rejectForm] = Form.useForm();

  useEffect(() => {
    fetchPendingTorrents();
  }, []);

  const fetchPendingTorrents = async () => {
    try {
      setLoading(true);
      const response = await getPendingTorrents();
      if (response.code === 200) {
        setTorrents(response.data.records || []);
      }
    } catch (error) {
      console.error('获取待审核种子失败:', error);
      message.error('获取待审核种子失败');
    } finally {
      setLoading(false);
    }
  };

  const handleApprove = async (torrentId: number) => {
    try {
      await approveTorrent(torrentId);
      message.success('种子审核通过');
      fetchPendingTorrents();
    } catch (error) {
      console.error('审核失败:', error);
      message.error('审核失败');
    }
  };

  const showRejectModal = (torrent: Torrent) => {
    setCurrentTorrent(torrent);
    setRejectModalVisible(true);
  };

  const handleReject = async (values: { reason: string }) => {
    if (!currentTorrent) return;
    
    try {
      await rejectTorrent(currentTorrent.id, values.reason);
      message.success('种子已拒绝');
      setRejectModalVisible(false);
      rejectForm.resetFields();
      fetchPendingTorrents();
    } catch (error) {
      console.error('拒绝失败:', error);
      message.error('拒绝失败');
    }
  };

  const getStatusTag = (status: number) => {
    const statusInfo = TORRENT_STATUS_MAP[status as keyof typeof TORRENT_STATUS_MAP];
    return (
      <Tag color={statusInfo?.color || 'default'}>
        {statusInfo?.text || '未知'}
      </Tag>
    );
  };

  const getPromotionTag = (promotionStatus: number) => {
    const promotionInfo = PROMOTION_STATUS_MAP[promotionStatus as keyof typeof PROMOTION_STATUS_MAP];
    if (!promotionInfo || promotionStatus === 0) return null;
    
    return (
      <Tag color={promotionInfo?.color || 'default'}>
        {promotionInfo?.text || '无'}
      </Tag>
    );
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '种子信息',
      dataIndex: 'title',
      key: 'title',
      render: (title: string, record: Torrent) => (
        <div>
          <Text strong>{title}</Text>
          <div style={{ marginTop: 4 }}>
            <Space split={<span>•</span>}>
              <Tag color="blue">{record.category}</Tag>
              {record.promotionStatus !== undefined && getPromotionTag(record.promotionStatus)}
              <Text type="secondary">
                上传者: {record.uploader || record.uploaderName}
              </Text>
            </Space>
          </div>
        </div>
      ),
    },
    {
      title: '文件大小',
      dataIndex: 'fileSize',
      key: 'fileSize',
      width: 120,
      render: (size: number, record: Torrent) => 
        formatBytes(size || record.size || 0),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: number) => getStatusTag(status),
    },
    {
      title: '上传时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      width: 160,
      render: (time: string, record: Torrent) => 
        formatDateTime(time || record.uploadedAt || ''),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (record: Torrent) => (
        <Space>
          <Button
            type="text"
            size="small"
            icon={<EyeOutlined />}
          >
            查看详情
          </Button>
          <Popconfirm
            title="确定通过审核吗？"
            onConfirm={() => handleApprove(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="text"
              size="small"
              icon={<CheckOutlined />}
              style={{ color: '#52c41a' }}
            >
              通过
            </Button>
          </Popconfirm>
          <Button
            type="text"
            size="small"
            icon={<CloseOutlined />}
            danger
            onClick={() => showRejectModal(record)}
          >
            拒绝
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card
        title={
          <Space>
            <CloudDownloadOutlined />
            <Title level={3} style={{ margin: 0 }}>种子管理</Title>
          </Space>
        }
        extra={
          <Button onClick={fetchPendingTorrents}>刷新</Button>
        }
      >
        <Table
          columns={columns}
          dataSource={torrents}
          rowKey="id"
          loading={loading}
          pagination={{
            pageSize: 20,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
          }}
        />
      </Card>

      {/* 拒绝种子模态框 */}
      <Modal
        title="拒绝种子"
        open={rejectModalVisible}
        onCancel={() => {
          setRejectModalVisible(false);
          rejectForm.resetFields();
        }}
        footer={null}
      >
        {currentTorrent && (
          <div>
            <p><strong>种子标题:</strong> {currentTorrent.title}</p>
            <p><strong>上传者:</strong> {currentTorrent.uploader || currentTorrent.uploaderName}</p>
            
            <Form
              form={rejectForm}
              layout="vertical"
              onFinish={handleReject}
            >
              <Form.Item
                label="拒绝理由"
                name="reason"
                rules={[
                  { required: true, message: '请输入拒绝理由' },
                  { min: 5, message: '拒绝理由至少5个字符' }
                ]}
              >
                <TextArea
                  rows={4}
                  placeholder="请详细说明拒绝的原因..."
                  maxLength={500}
                  showCount
                />
              </Form.Item>
              <Form.Item>
                <Space>
                  <Button type="primary" htmlType="submit">
                    确定拒绝
                  </Button>
                  <Button onClick={() => {
                    setRejectModalVisible(false);
                    rejectForm.resetFields();
                  }}>
                    取消
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default TorrentManagement; 